#############################################################################
#Yuhua Wang#
#The Rise and Fall of Imperial China: The Social Origins of State Development#
#Princeton University Press, 2022#
############################################################################

############################################################################
#Chapter 2#
############################################################################


######################################
#Figure 2.2: Temperature Anomalies and Conflict (0–1900)#
######################################

rm(list = ls())

library(foreign) 
library(ggplot2) 
library(ggrepel) 
require(gridExtra)

set.seed(12349)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

longtermdata <- read.dta("longterm trends.dta")

attach(longtermdata)

externalwar <-ggplot(data=longtermdata, aes(x=year, y=externalwar)) +
  geom_bar(stat="identity", width=10,color="#F65737", fill="#F65737")+
  scale_fill_brewer(palette="Paired")+
  theme_bw()+
  theme(text = element_text(size=8))+
  scale_x_continuous(name="Year", limits=c(0,1900), breaks=c(0,100,200,300,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900)) +
  scale_y_continuous(name="Number of External Wars",limits=c(0,40), breaks=c(0,5,10,15,20,25,30,35,40))

peasantreb <- ggplot(data=longtermdata, aes(x=year, y=peasantreb)) +
  geom_bar(stat="identity", width=10,color="#61BAF6", fill="#61BAF6")+
  scale_fill_brewer(palette="Paired")+
  theme_bw()+
  theme(text = element_text(size=8))+
  scale_x_continuous(name="Year", limits=c(0,1900), breaks=c(0,100,200,300,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900)) +
  scale_y_continuous(name="Number of Mass Rebellions",limits=c(0,40), breaks=c(0,5,10,15,20,25,30,35,40))


templine <- ggplot(data=longtermdata, aes(x=year, y=temppls)) +
  geom_point(aes(colour = temppls)) +
  scale_colour_gradient2(low = "blue", mid = "green" , high = "red", midpoint = 0) + 
  geom_smooth(colour = "red",size = 1) +
  geom_hline(yintercept=0, linetype="dashed", color = "black")+
  scale_x_continuous(name="Year", limits=c(0,1900), breaks=c(0,100,200,300,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900)) +
  scale_y_continuous(name="Temperature Anomalies (°C)",limits=c(-0.5,0.5), breaks=c(-0.5,0,0.5))+
  theme_bw()+
  theme(text = element_text(size=8))+
  theme(legend.position = "none")

grid.arrange(templine,peasantreb, externalwar, ncol=1)
c <- arrangeGrob(templine,peasantreb, externalwar, ncol=1)


######################################
#Figure 2.5: Tang Elite Social Terrain#
######################################

######################################
#(a) Tang Elite Marriage Network (750–850)#
######################################

rm(list = ls())
library(statnet)
library("network")

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

set.seed(12349)

#Read in Tackett's Adjacency Matrix

net.adj.tackett<-read.csv(file="adjacency_matrix_tackett.csv",header=FALSE,stringsAsFactors=FALSE)

net.adj.tackett <- as.matrix(net.adj.tackett) 

# load in vertex attributes
nodeInfoTackett <- read.csv(file="vertexAttributesTackett.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.tackett) # peek at matrix 
print(nodeInfoTackett)  # peek at attribute data

# Since our relational data has no row/column names, let's set them now
rownames(net.adj.tackett) <- nodeInfoTackett$choronym_surname_no
colnames(net.adj.tackett) <- nodeInfoTackett$choronym_surname_no

print(net.adj.tackett)

# create undirected network object from matrix

net_tackett<-network(net.adj.tackett, directed=FALSE, matrix.type="adjacency")

# it read in vertex names from matrix col names ...
network.vertex.names(net_tackett)

# ATTACHING VERTEX ATTRIBUTES

# ... but could also set vertex.names with 
net_tackett%v%'vertex.names'<- nodeInfoTackett$choronym_surname_no

# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_tackett)

summary(net_tackett)

gden(net_tackett)

#0.02827965

# centrality measures

deg_tackett<-degree(net_tackett,gmode="graph")
deg_tackett

deg_tackett.data<-data.frame(deg_tackett)
deg_tackett.data

btw_tackett<-betweenness(net_tackett,gmode="graph")
btw_tackett

btw_tackett.data<-data.frame(btw_tackett)
btw_tackett.data

# graphs

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}

mycoords1 <- gplot(net_tackett,gmode="graph", vertex.cex=1.5)

op<-par(mar=c(0,0,0,0))
gplot(net_tackett,gmode="graph", coord=mycoords1, vertex.col="#DF536B", 
      vertex.cex=rescale(deg_tackett,0.5,3), edge.col="grey80",suppress.axes=TRUE,
      ylim=c(min(mycoords1[,2])-1,max(mycoords1[,2])+1),
      mode="fruchtermanreingold")
par(op)

######################################
#(b) Tang Elites and their Kin (779–805)#
######################################

rm(list = ls())
library(foreign) 
library(ggplot2) 
require(ggplot2)
library(ggrepel) 
library(plyr)
require(scales)
library(igraph)
library(statnet)
library("network")

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

set.seed(12349)

#read in egelist
rawedgestang<-read.csv("tang edgelist.csv")

#turn edgelist into adjacency matrix
matrixtang <-as.matrix(get.adjacency(graph.data.frame(rawedgestang)))

#write in a csv file
write.csv(matrixtang,"tang adjmatrix.csv", row.names = FALSE)

# detach igraph package
detach("package:igraph")

#Read in Adjacency Matrix

net.adj.tang <- as.matrix(matrixtang) 

# load in vertex attributes

#orignal coordinates
nodeInfoTang <- read.csv(file="tang vertex.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.tang) # peek at matrix 
print(nodeInfoTang)  # peek at attribute data

# create undirected network object from matrix

net_tang<-network(net.adj.tang, directed=FALSE, matrix.type="adjacency")

# it read in vertex names from matrix col names ...
network.vertex.names(net_tang)

# ATTACHING VERTEX ATTRIBUTES

# load in other attributes 
net_tang%v%"lon" <- nodeInfoTang$X
net_tang%v%"lat" <- nodeInfoTang$Y
net_tang%v%"name" <- nodeInfoTang$name_pinyin
net_tang%v%"ego" <- nodeInfoTang$ego


# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_tang)

summary(net_tang)

gden(net_tang)

deg <- degree(net_tang,gmode="graph")

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}

# Add Tang map

library('maps')
library('geosphere')
library(maptools)
library(foreign)
library(PBSmapping)
library(network)
library(maps)
library(statnet)
require(rgdal)

#Shapefile#

tang <- importShapefile("_tang_with_provinces_r9w.shp")

proj.abbr <- attr(tang, "projection")

plotPolys(tang, projection=proj.abbr, border="grey",
          xlab="", ylab="",col="#f5f5f2", tckLab = FALSE,axes=FALSE)

#Network on map

plot.network(net_tang,  # pass in the network
             # don't erase the map before drawing the network
             new=FALSE, 
             # get coordiantes from vertices and pass in as 2-col matrix
             coord=cbind(net_tang%v%"lon",net_tang%v%"lat"),  
             # ---- all the rest of these are optional to make it look nice ------
             # set a semi-transparent edge color
             vertex.cex=rescale(deg,1,6),
             vertex.col="darkred",
             usecurve=TRUE,
             edge.col="grey",
             edge.curve = 0.01,
             # please don't jitter the points around
             jitter=FALSE)


######################################
#Figure 2.6: Song Elite Social Terrain#
######################################

######################################
#(a) Song Elite Marriage Network (997–1022)#
######################################

#preface#
rm(list = ls())
library(statnet)
library("network")
set.seed(12346)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

#Read in Song Officials' Adjacency Matrix

net.adj.song<-read.csv(file="all song officials adj matrix.csv",header=FALSE,stringsAsFactors=FALSE)

net.adj.song <- as.matrix(net.adj.song) 

# load in vertex attributes
nodeInfosong <- read.csv(file="all song officials vertex attributes.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.song) # peek at matrix 
print(nodeInfosong)  # peek at attribute data

# Since our relational data has no row/column names, let's set them now
rownames(net.adj.song) <- nodeInfosong$name_pinyin
colnames(net.adj.song) <- nodeInfosong$name_pinyin

print(net.adj.song)

# create undirected network object from matrix

net_official_song<-network(net.adj.song, directed=FALSE, matrix.type="adjacency")

# it read in vertex names from matrix col names ...
network.vertex.names(net_official_song)

# ATTACHING VERTEX ATTRIBUTES

# ... but could also set vertex.names with 
net_official_song%v%'vertex.names'<- nodeInfosong$name_pinyin

# load in emperor reigns 

net_official_song%v%"reign1" <- nodeInfosong$reign1
net_official_song%v%"reign2" <- nodeInfosong$reign2
net_official_song%v%"reign3" <- nodeInfosong$reign3
net_official_song%v%"reign4" <- nodeInfosong$reign4
net_official_song%v%"reign5" <- nodeInfosong$reign5
net_official_song%v%"reign6" <- nodeInfosong$reign6
net_official_song%v%"reign7" <- nodeInfosong$reign7
net_official_song%v%"reign8" <- nodeInfosong$reign8
net_official_song%v%"reign9" <- nodeInfosong$reign9
net_official_song%v%"reign10" <- nodeInfosong$reign10
net_official_song%v%"reign11" <- nodeInfosong$reign11
net_official_song%v%"reign12" <- nodeInfosong$reign12
net_official_song%v%"reign13" <- nodeInfosong$reign13
net_official_song%v%"reign14" <- nodeInfosong$reign14
net_official_song%v%"reign15" <- nodeInfosong$reign15
net_official_song%v%"reign16" <- nodeInfosong$reign16
net_official_song%v%"reign17" <- nodeInfosong$reign17


# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_official_song)

summary(net_official_song)

# graphs

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}

#we want to show the network during reign3	(Zhenzong (997-1022))
net_songofficial_reign3<-get.inducedSubgraph(net_official_song,eid=which(net_official_song%v%'reign3'==1))

summary(net_songofficial_reign3)
gden_net_songofficial_reign3 <- data.frame(table(gden(net_songofficial_reign3)))

gden(net_songofficial_reign3)
#0.01101658

deg_song_r3<-degree(net_songofficial_reign3,gmode="graph")
deg_song_r3

op<-par(mar=c(0,0,0,0))
plot(net_songofficial_reign3,vertex.col="#DF536B", vertex.cex=rescale(deg_song_r3,0.5,3), edge.col="grey80", mode="fruchtermanreingold")
par(op)

######################################
#(b) Song Elites and their Kin (997–1022)#
######################################

rm(list = ls())

library(statnet)
library("network")
library(igraph)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

set.seed(12349)

#Constructing adj matrix of Zhenzong (997-1022) officials

#read in egelist of officials with kinship ties

Sys.setlocale(locale = "en_us.UTF-8")
edge.list.woisolates <- read.table("zhenzong officials and kin edgelist.csv",
                                   sep=",",
                                   header=TRUE, 
                                   encoding="UTF-8", 
                                   stringsAsFactors=FALSE)

## plot edge-list data
graph.woisolates <- graph.data.frame(edge.list.woisolates, directed=FALSE) 

plot(graph.woisolates,vertex.cex=0.01)

## convert to adjacency list
adj.zhenzong.woisolates<- get.adjacency(graph.woisolates, type="both") 

## convert to matrix
matrix.zhenzong.woisolates <- as.matrix(adj.zhenzong.woisolates) 

##output as csv file
write.csv(matrix.zhenzong.woisolates,file="adjmatrix_zhenzong_woisolates.csv")

#delete the first row and first column with the ids and save as adjmatrix_zhenzong.csv

# detach igraph package
detach("package:igraph")

# read in the adjacency matrix and convert to matrix
net.adj.zhenzong<-read.csv(file="adjmatrix_zhenzong.csv",header=FALSE,stringsAsFactors=FALSE)
net.adj.zhenzong <- as.matrix(net.adj.zhenzong) 

# load in vertex attributes (make sure the sequence conform to the adjacency matrix)
nodeInfozhenzong <- read.csv(file="Zhenzong vertex attributes.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.zhenzong) # peek at matrix 
print(nodeInfozhenzong)  # peek at attribute data

# Since our relational data has no row/column names, let's set them now
rownames(net.adj.zhenzong) <- nodeInfozhenzong$name_pinyin
colnames(net.adj.zhenzong) <- nodeInfozhenzong$name_pinyin

print(net.adj.zhenzong)

# create undirected network object from matrix

net_official_zhenzong<-network(net.adj.zhenzong, directed=FALSE, matrix.type="adjacency")

# it read in vertex names from matrix col names ...
network.vertex.names(net_official_zhenzong)

# ATTACHING VERTEX ATTRIBUTES

# ... but could also set vertex.names with 
net_official_zhenzong%v%'vertex.names'<- nodeInfozhenzong$name_pinyin

# load in other attributes #NOT DONE YET
net_official_zhenzong%v%"x" <- nodeInfozhenzong$x
net_official_zhenzong%v%"y" <- nodeInfozhenzong$y


# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_official_zhenzong)

summary(net_official_zhenzong)

# centrality measures

deg_zhenzong<-degree(net_official_zhenzong,gmode="graph")
deg_zhenzong

deg_zhenzong.data<-data.frame(deg_zhenzong)
deg_zhenzong.data


# graph for all the Zhenzong officials

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}

op<-par(mar=c(0,0,0,0))
plot(net_official_zhenzong,vertex.col="#DF536B", vertex.cex=rescale(deg_zhenzong,0.5,3))
par(op)

# Add Northern Song map

library('maps')
library('geosphere')
library(maptools)
library(foreign)
library(PBSmapping)
library(network)
library(maps)
library(statnet)
require(rgdal)

#Set colors#

t_col <- function(color, percent = 50, name = NULL) {
  #      color = color name
  #    percent = % transparency
  #       name = an optional name for the color
  
  ## Get RGB values for named color
  rgb.val <- col2rgb(color)
  
  ## Make new color using input color as base and alpha set by transparency
  t.col <- rgb(rgb.val[1], rgb.val[2], rgb.val[3],
               max = 255,
               alpha = (100 - percent) * 255 / 100,
               names = name)
  
  ## Save the color
  invisible(t.col)
}
## END

mycol <- t_col("lightgrey", perc = 50, name = "lt.grey")

#Shapefile#

song <- importShapefile("Northern Song borders.shp")

proj.abbr <- attr(song, "projection")

plotPolys(song, projection=proj.abbr, border="grey",
          xlab="", ylab="",col="#f5f5f2", tckLab = FALSE,axes=FALSE)

#Network on map

plot.network(net_official_zhenzong,  # pass in the network
             # don't erase the map before drawing the network
             new=FALSE, 
             # get coordiantes from vertices and pass in as 2-col matrix
             coord=cbind(net_official_zhenzong%v%"x",net_official_zhenzong%v%"y"),  
             # ---- all the rest of these are optional to make it look nice ------
             # set a semi-transparent edge color
             mode = "fruchtermanreingold",
             vertex.col="red",
             vertex.cex=rescale(deg_zhenzong,0.5,4),
             edge.col=mycol,
             edge.lwd=0.01,
             usecurve=FALSE,
             # please don't jitter the points around
             jitter=FALSE)


######################################
#Figure 2.7: Growth of Clan Collective Action#
######################################

######################################
#(a) Number of Genealogical Records Compiled Every Year (1000–1900)#
######################################

rm(list = ls())

library(foreign) 
library(ggplot2) 
library(ggrepel) 
require(gridExtra)

set.seed(12349)


#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

genealogy <- read.dta("genealogy movingaverage.dta")

attach(genealogy)

genealogy <- ggplot(data=genealogy) + 
  geom_line(aes(x=yearofcompiling, y=smoothgenealogy, color="#F65737",linetype="solid"), size=1)+
  scale_x_continuous(name="Year of Compilation", limits=c(1000,1950), breaks=c(1000,1100,1200,1300,1400,1500,1600,1700,1800,1900)) +
  scale_y_continuous(name="Number",limits=c(0,130), breaks=c(0,10,20,30,40,50,60,70,80,90,100,110,120,130)) +
  geom_vline(xintercept = 1850,color="black",linetype="dashed")+ 
  geom_vline(xintercept = 1644,color="black",linetype="dashed")+ 
  geom_vline(xintercept = 1368,color="black",linetype="dashed")+ 
  geom_vline(xintercept = 1279,color="black",linetype="dashed")+ 
  annotate(geom="text", x = 1140, y=50, label = "Song", size=3, fontface="bold")+
  annotate(geom="text", x = 1500, y=50, label = "Ming", size=3, fontface="bold")+
  annotate(geom="text", x = 1750, y=50, label = "Early", size=3, fontface="bold")+
  annotate(geom="text", x = 1750, y=40, label = "Qing", size=3, fontface="bold")+
  annotate(geom="text", x = 1920, y=50, label = "Late", size=3, fontface="bold")+
  annotate(geom="text", x = 1920, y=40, label = "Qing", size=3, fontface="bold")+
  theme_bw()+
  theme(legend.position="none")+
  theme(text = element_text(size=10, 
                            vjust=1))

genealogy

######################################
#(b) Number of Genealogical Records in the Late Qing Era (1800–1900)#
######################################


rm(list = ls())
library(foreign) 
library(ggplot2) 
require(ggplot2)
library(ggrepel) 
library(plyr)
require(scales)
require(gridExtra)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

taipingts <- read.dta("timeseries 1000-1900.dta")

attach(taipingts)

taiping <- ggplot(data=taipingts, aes(x=year, y=massrebellion, color="black",linetype="solid")) + 
  geom_line(color="black",size=1) +
  scale_x_continuous(name="Year", limits=c(1800,1900), breaks=c(1800,1810,1820,1830,1840,1850,1860,1870,1880,1890,1900)) +
  scale_y_continuous(name="N of Mass Rebellions",limits=c(0,40), breaks=c(0,5,10,15,20,25,30,35,40)) +
  theme_bw()+
  theme(legend.position="none")+
  theme(text = element_text(size=15, 
                            vjust=1, family="Times"))+ 
  geom_vline(xintercept = 1850,color="black",linetype="dashed")+ 
  geom_vline(xintercept = 1869,color="black",linetype="dashed")+ 
  annotate(geom="text", x = 1860, y=40, label = "Taiping",size=5, family="Times",fontface =2)+
  annotate(geom="text", x = 1860, y=36, label = "Rebellion",size=5, family="Times",fontface =2)

genealogy <- ggplot(data=taipingts, aes(x=year, y=genealogy, color="black",linetype="solid")) + 
  geom_line(color="black",size=1) +
  scale_x_continuous(name="Year", limits=c(1800,1900), breaks=c(1800,1810,1820,1830,1840,1850,1860,1870,1880,1890,1900)) +
  scale_y_continuous(name="N of Genealogy Books",limits=c(0,300), breaks=c(0,100,200,300)) +
  theme_bw()+
  theme(legend.position="none")+
  theme(text = element_text(size=15, 
                            vjust=1, family="Times"))+ 
  geom_vline(xintercept = 1850,color="black",linetype="dashed")+ 
  geom_vline(xintercept = 1869,color="black",linetype="dashed")

grid.arrange(taiping, genealogy, ncol=1)
a <- arrangeGrob(taiping, genealogy, ncol=1)


######################################
#Figure 2.8: Fiscal Policies and Per Capita Taxation (0–1900)#
######################################

rm(list = ls())

library(foreign) 
library(ggplot2) 
library(ggrepel) 
require(gridExtra)

set.seed(12349)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

longtermdata <- read.dta("longterm trends.dta")

attach(longtermdata)

policy <- ggplot(data=longtermdata, aes(x=year, y=smoothpolicy)) + 
  geom_line(linetype = "solid", size=0.8) + 
  scale_color_manual(values=c("#F8766D"))+
  scale_x_continuous(name="Year", limits=c(0,1900), breaks=c(0,100,200,300,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900)) +
  scale_y_continuous(name="Fiscal Policies (Weakening-Strengthening)",limits=c(-0.5,1), breaks=c(-0.5,0,0.5,1))+
  theme(legend.position="none")+
  theme_bw()+
  theme(text = element_text(size=7))


tax <- ggplot(data=longtermdata, aes(x=year, y=pctax)) +
  geom_bar(stat="identity", width=10)+
  scale_fill_brewer(palette="Paired")+
  theme_bw()+
  theme(text = element_text(size=7))+
  scale_x_continuous(name="Year", limits=c(0,1900), breaks=c(0,100,200,300,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900)) +
  scale_y_continuous(name="Per Capita Tax (dan of rice)",limits=c(0,4), breaks=c(0,1,2,3,4))

grid.arrange(policy, tax, ncol=1)
a <- arrangeGrob(policy, tax, ncol=1)

######################################
#Figure 2.9: Taxation as a Share of GDP: China vs. England (1000–1900)#
######################################

rm(list = ls())

library(foreign) 
library(ggplot2) 
library(ggrepel) 
require(gridExtra)

set.seed(12349)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

chinaengland <- read.dta("China England taxation gdp.dta")

chinaengland <- ggplot(data=chinaengland) +
  geom_bar(aes(x=year, y=chinapercent), position="stack", color = "#F65737", fill="#F65737", stat="identity", width=10)+
  geom_line(data=chinaengland[!is.na(chinaengland$englandpercent),],aes(x = year, y = englandpercent), size=1, color="#61BAF6")+
  theme_bw()+
  theme(text = element_text(size=10))+
  scale_x_continuous(name="Year", limits=c(950,1950), breaks=c(1000,1100,1200,1300,1400,1500,1600,1700,1800,1900)) +
  scale_y_continuous(name="Taxation as Share of GDP (%)",limits=c(0,20), breaks=c(0,5,10,15,20))+
  annotate(geom="text", x = 1900, y=2.5, label = "China",size=3, fontface =2)+
  annotate(geom="text", x = 1900, y=12.5, label = "England", size=3, fontface =2)

chinaengland

######################################
#Figure 2.10: Probability of Ruler Deposal by Elites (0–1900)#
######################################

rm(list = ls())

library(foreign) 
library(ggplot2) 
library(ggrepel) 
require(gridExtra)

set.seed(12349)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

chinaruler <- read.dta("Chinese rulers.dta")

attach(chinaruler)

rulerdeposed <- ggplot(data=chinaruler) + 
  geom_line(aes(x=officestartingyear, y=smootheddepose, color="#F65737",linetype="solid"), size=1)+
  scale_x_continuous(name="Year of Ascension", limits=c(10,1900), breaks=c(0,200,400,600,800,1000,1300,1500,1700,1900)) +
  scale_y_continuous(name="Probability of being Deposed by Elites",limits=c(0,0.5), breaks=c(0,0.1,0.2,0.3,0.4,0.5)) +
  geom_vline(xintercept = 1644,color="black",linetype="dashed")+ 
  geom_vline(xintercept = 1368,color="black",linetype="dashed")+ 
  geom_vline(xintercept = 1279,color="black",linetype="dashed")+ 
  geom_vline(xintercept = 960,color="black",linetype="dashed")+ 
  geom_vline(xintercept = 907,color="black",linetype="dashed")+ 
  geom_vline(xintercept = 618,color="black",linetype="dashed")+
  geom_vline(xintercept = 220,color="black",linetype="dashed")+
  annotate(geom="text", x = 90, y=0.48, label = "Han",size=3,fontface="bold")+
  annotate(geom="text", x = 400, y=0.48, label = "Multiple",size=2.5,fontface="bold")+
  annotate(geom="text", x = 410, y=0.46, label = "Fragmented",size=2.5,fontface="bold")+
  annotate(geom="text", x = 400, y=0.44, label = "Dynasties",size=2.5,fontface="bold")+
  annotate(geom="text", x = 780, y=0.48, label = "Tang",size=3,fontface="bold")+
  annotate(geom="text", x = 1140, y=0.48, label = "Song", size=3, fontface="bold")+
  annotate(geom="text", x = 1500, y=0.48, label = "Ming", size=3, fontface="bold")+
  annotate(geom="text", x = 1800, y=0.48, label = "Qing", size=3, fontface="bold")+
  theme_bw()+
  theme(legend.position="none")+
  theme(text = element_text(size=10, 
                            vjust=1))

rulerdeposed


######################################
#Figure 2.11: Ruler Survival in China, Europe, and the Islamic World (1000–1800)#
######################################

rm(list = ls())

library(foreign) 
library(ggplot2) 
library(ggrepel) 
require(gridExtra)

set.seed(12349)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 2/data/")

ruler <- read.dta("ruler moving averages.dta")

attach(ruler)

ruler$treatment <- as.factor(ruler$region_dis)

plot1 <- ggplot(data=ruler, aes(x=ascension, y=smoothedduration,group=treatment,color=treatment)) + 
  geom_line(linetype = "solid", size=0.8) + 
  scale_color_manual(values=c("#F65737",  "#61BAF6", "#00BA38"))+
  scale_x_continuous(name="Year of Ascension", limits=c(1000,1800), breaks=c(1000,1100,1200,1300,1400,1500,1600,1700,1800)) +
  scale_y_continuous(name="Duration",limits=c(10,20), breaks=c(10,15,20))+
  theme_bw()+
  theme(legend.position="none")+
  theme(text = element_text(size=10, 
                            vjust=1))+
  annotate(geom="text", x = 1700, y=18.2, label = "Europe",size=3, fontface="bold")+
  annotate(geom="text", x = 1700, y=14.5, label = "China", size=3, fontface="bold")+
  annotate(geom="text", x = 1700, y=11.5, label = "Islamic World", size=3, fontface="bold")


plot2 <- ggplot(data=ruler, aes(x=ascension, y=smootheddepose,group=treatment,color=treatment)) + 
  geom_line(linetype = "solid", size=0.8) + 
  scale_color_manual(values=c("#F65737",  "#61BAF6", "#00BA38"))+
  scale_x_continuous(name="Year of Ascension", limits=c(1000,1800), breaks=c(1000,1100,1200,1300,1400,1500,1600,1700,1800)) +
  scale_y_continuous(name="Probability Deposed",limits=c(0.2,0.6), breaks=c(0.2,0.4,0.6))+
  theme_bw()+
  theme(legend.position="none")+
  theme(text = element_text(size=10, 
                            vjust=1))+
  annotate("text", x = 1700, y=0.37, label = "Europe",size=3, fontface="bold")+
  annotate("text", x = 1700, y=0.2,  label = "China", size=3, fontface="bold")+
  annotate("text", x = 1700, y=0.59, label = "Islamic World", size=3, fontface="bold")

grid.arrange(plot1, plot2, ncol=1)
r <- arrangeGrob(plot1, plot2, ncol=1)

